#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import datetime
import urllib.request
import requests

import cssutils

from bs4 import BeautifulSoup
from selenium import webdriver

from PIL import Image

def downBingImg(url):
    res = urllib.request.urlopen(url)


    # 指定 ChromeDriver 的路径
    driver_path = "/home/hwj/Documents/github/scheduled-download-image/chromedriver"

    # 创建 ChromeDriver 的 Service 对象
    service = webdriver.chrome.service.Service(driver_path)

    # 启动 ChromeDriver
    service.start()

    # 使用 ChromeDriver 创建浏览器实例
    driver = webdriver.Chrome(service=service)
    
    #driver = webdriver.Chrome("./chromedriver")
    driver.get(url)  # 替换为您要访问的网页URL

    # 获取动态生成的HTML内容
    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")

    # 获取下载链接
    downloadUrl = parse_style_attribute(soup.select(".img_cont")[0].get('style'))
    #downloadUrl = url + downloadUrl

    # 获取背景图片名称
    imageName = soup.select(".musCardCont .title")[0].text;
    imageName = datetime.datetime.now().strftime('%Y-%m-%d') + " " + imageName

    print(imageName + ":>>> " + downloadUrl)
    # 下载图片
    #urllib.request.urlretrieve(downloadUrl, '/home/hwj/Pictures/bing-pictrues/%s.jpg' % imageName)
    response = requests.get(downloadUrl)

    filename = 'image.webp' 
    with open(filename, 'wb') as f:
        f.write(response.content)

    # 将.webp文件转换为图片文件并保存到磁盘
    image = Image.open(filename)
    image = image.convert('RGB')
    image.save('/home/hwj/Pictures/bing-pictrues/%s.jpg' % imageName, 'JPEG')
    
    # 关闭浏览器
    driver.quit()

    # 停止 ChromeDriver
    service.stop()

# 从background-image: url('**') 提取url
def parse_style_attribute(style_string):
    sheet = cssutils.css.CSSStyleSheet()
    
    #删除与url无关的style
    style_string = style_string.split(";")[0]
    sheet.add("dummy_selector { %s }" % style_string)
    
    url = list(cssutils.getUrls(sheet))[0]
    return url

if __name__ == '__main__':
    url = 'https://cn.bing.com/'
    downBingImg(url)
